package com.jianyun.jyzs.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hannesdorfmann.mosby3.mvp.MvpActivity;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.adapter.CommentAdapter;
import com.jianyun.jyzs.base.MVPBaseActivity;
import com.jianyun.jyzs.bean.AnnouncementComment;
import com.jianyun.jyzs.bean.AnnouncementList;
import com.jianyun.jyzs.dao.AnnCommentDao;
import com.jianyun.jyzs.dao.AnnouncementDao;
import com.jianyun.jyzs.presenter.AnnoounceDetailPresenter;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.Utils;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.view.iview.IAnnounceDetailView;
import com.jianyun.jyzs.widget.FullyLinearLayoutManager;
import com.jrmf360.rylib.common.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import com.jianyun.jyzs.utils.RceLog;

/**
 * 通知公告详情界面
 * Created by yangshijun on 2018/5/29.
 */

public class AnnouncementDetialActivity extends MvpActivity<IAnnounceDetailView,
        AnnoounceDetailPresenter> implements IAnnounceDetailView, View.OnClickListener {

    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;
    @BindView(R.id.tv_checked)
    TextView tvChecked;
    @BindView(R.id.tv_update)
    TextView tvUpdate;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.iv_moreLinearLayout)
    LinearLayout ivMoreLinearLayout;
    @BindView(R.id.topCreat)
    LinearLayout topCreat;
    @BindView(R.id.iv_single)
    ImageView ivSingle;
    @BindView(R.id.iv_group)
    ImageView ivGroup;
    @BindView(R.id.topChatDetail)
    LinearLayout topChatDetail;
    @BindView(R.id.topId)
    RelativeLayout topId;
    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.list_comment)
    RecyclerView listComment;
    @BindView(R.id.et_comment)
    EditText etComment;
    @BindView(R.id.tv_send)
    TextView tvSend;
    @BindView(R.id.iv_comment)
    TextView ivComment;
    @BindView(R.id.tv_likes)
    TextView tvLikes;
    @BindView(R.id.ll_toDiscuss)
    LinearLayout llToDiscuss;
    @BindView(R.id.relativeLayout)
    RelativeLayout relativeLayout;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;


    private AnnouncementList.Announcement bean;
    private AnnCommentDao dao;
    private CommentAdapter adapter;
    private List<AnnouncementComment.AnnComment> commentList = new ArrayList<>();
    private HashMap<String, String> map = new HashMap<>();
    private AnnouncementDao announcementDao;
    public boolean mark = false;
    public ProgressDialog dialog;
    private String enterpriseCode;
    private String userId;
    private String username;
    private String newsId;
    private int agresNum;
    private boolean askedgalleryPermission = false;
    private int galleryPermissionReqCode = 202;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_announcement_detial);
        ButterKnife.bind(this);
        UtilsStyle.setStatusBarMode(this, true);
        initData();
        initView();
        setCommentView();
        initWebView();
        initLinstner();
        getCommentList();


    }

    private void getCommentList() {
        HashMap<String, String> map = new HashMap<>();
        if (newsId == null) {
            map.put("newsId", bean.getNewsId());
        } else {
            map.put("newsId", newsId);
        }
        map.put("lateId", "0");
        progressBar.setVisibility(View.VISIBLE);

        //  获取评论数据
        //getPresenter().getAccounceComment(dao, map, enterpriseCode);
    }

    private void initData() {
        newsId = getIntent().getStringExtra("newsId");
        if (newsId == null) {
            bean = (AnnouncementList.Announcement) getIntent().getSerializableExtra("bundle");
            enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
            userId = LoginCache.getInstance().getUserInfo().getUserId();
            username = LoginCache.getInstance().getUserDetaileInfo().getName();
            bean.setIsread(true);
            new AnnouncementDao(this).update(bean);//更新已读状态
            dao = new AnnCommentDao(this);
            announcementDao = new AnnouncementDao(this);
            listComment.setLayoutManager(new FullyLinearLayoutManager(this));
            adapter = new CommentAdapter(this, null);
        } else {
            //bean = (AnnouncementList.Announcement) getIntent().getSerializableExtra("bundle");
            enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
            userId = LoginCache.getInstance().getUserInfo().getUserId();
            username = LoginCache.getInstance().getUserDetaileInfo().getName();
            //bean.setIsread(true);
            //new AnnouncementDao(this).update(bean);//更新已读状态
            dao = new AnnCommentDao(this);
            announcementDao = new AnnouncementDao(this);
            listComment.setLayoutManager(new FullyLinearLayoutManager(this));
            adapter = new CommentAdapter(this, null);
        }

    }

    private void initView() {

        listComment.setAdapter(adapter);
        topBack.setVisibility(View.VISIBLE);
        topText.setVisibility(View.VISIBLE);
        topBack.setOnClickListener(this);
        topText.setText("公告详情");

    }

    private void initWebView() {
        WebSettings webSettings = webview.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(false);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        /*webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setBuiltInZoomControls(true);
        if (Build.VERSION.SDK_INT > 11) {
            webSettings.setDisplayZoomControls(false);
        }
        webSettings.setSupportZoom(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);*/
        String url;
        if (newsId == null) {
            url = LoginCache.getInstance().getLoginCache().getErpRootUrl() + "/" + bean.getUrl();
        } else {
            url = LoginCache.getInstance().getLoginCache().getErpRootUrl() + "DataService/DetailRecord.html?id=" + newsId;
        }

        Log.i("test", "加载需要显示的网页" + url);
        //加载需要显示的网页
        webview.loadUrl(url);
        //设置Web视图
        webview.setWebViewClient(new webViewClient());
        webview.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {

                return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
            }
        });
        webview.setDownloadListener(new MyWebViewDownLoadListener());


    }


    private void initLinstner() {
        tvLikes.setOnClickListener(this);
        tvSend.setOnClickListener(this);
        relativeLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //比较Activity根布局与当前布局的大小
                int heightDiff = relativeLayout.getRootView().getHeight() - relativeLayout.getHeight();
                if (heightDiff > 100) {
                    if (!mark) {
                        tvSend.setVisibility(View.VISIBLE);
                        ivComment.setVisibility(View.GONE);
                        tvLikes.setVisibility(View.GONE);
                        mark = true;
                    }
                } else {
                    if (mark) {
                        tvSend.setVisibility(View.GONE);
                        ivComment.setVisibility(View.VISIBLE);
                        tvLikes.setVisibility(View.VISIBLE);
                        mark = false;
                    }
                }
            }
        });
    }

    private void setCommentView() {
        setLiksView();
        if (newsId == null) {
            commentList = dao.getAnnCommentList(bean.getNewsId(), enterpriseCode);
        } else {
            commentList = dao.getAnnCommentList(newsId, enterpriseCode);
        }
        if (commentList.size() > 0) ivComment.setText(commentList.size() + "");
        adapter.setList(commentList);
    }

    private void setLiksView() {
        if (newsId == null) {
            int agreeCount = bean.getAgreeCount();
            if (agreeCount > 0) tvLikes.setText(agreeCount + "");
        } else {
            if (agresNum > 0) tvLikes.setText(agresNum + "");
        }

    }

    @NonNull
    @Override
    public AnnoounceDetailPresenter createPresenter() {
        return new AnnoounceDetailPresenter();
    }

    @Override
    public void showLoading() {
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void hintLoading() {
        progressBar.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onCommitLikeSuccess() {
        if (newsId == null) {
            int agreeCount = bean.getAgreeCount();
            bean.setAgreeCount(agreeCount + 1);
            announcementDao.update(bean);
            setLiksView();
        } else {

        }

    }

    @Override
    public void onCommitAnnounceSuccess() {
        if (newsId == null) {
            bean.setMsgCount(bean.getMsgCount() + 1);
            announcementDao.update(bean);
            getCommentList();
            etComment.setText(null);
            Utils.closeKeyBoard(this, tvSend);
        } else {

        }

    }

    @Override
    public void onSuccess() {
        setCommentView();
    }

    @Override
    public void onFailed(String msg) {
        ToastUtil.showNoWaitToast(this, msg);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.topBack:
                finish();
                break;
            case R.id.tv_likes:
                map.clear();
                map.put("enterpriseCode", enterpriseCode);
                map.put("userId", userId);
                map.put("userName", username);
                if (newsId == null) {
                    map.put("newsId", bean.getNewsId());
                } else {
                    map.put("newsId", newsId);
                }

                //getPresenter().commmitLike(map);
                break;
            case R.id.tv_send:
                String content = etComment.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    ToastUtil.showNoWaitToast(this, "评论不可为空");
                    return;
                }
                map.put("enterpriseCode", enterpriseCode);
                map.put("userId", userId);
                map.put("name", username);
                if (newsId == null) {
                    map.put("newsId", bean.getNewsId());
                } else {
                    map.put("newsId", newsId);
                }
                map.put("text", content);
                //getPresenter().commitComment(map);
                break;
        }
    }

    class MyWebViewDownLoadListener implements DownloadListener {
        @Override
        public void onDownloadStart(String s, String s1, String s2, String s3, long l) {
            showFile(s);
        }
    }

    public void showFile(String url) {
        Log.i("test", "下载：" + url);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            //有权限
            //其他手机 下载 打开
            startActivity((new Intent(this, ShowFileActivity.class))
                    .putExtra("type", -1)
                    .putExtra("id", -1)
                    .putExtra("folderID", "workFlow")
                    .putExtra("remotepath", url));
        } else if (!askedgalleryPermission) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    galleryPermissionReqCode);
            askedgalleryPermission = true;
        }
    }

    private class webViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//网页页面开始加载的时候
            super.onPageStarted(view, url, favicon);
            /*if (dialog == null) {
                dialog.setMessage(getString(R.string.load_text));
                dialog.setCanceledOnTouchOutside(false);
            }
            dialog.show();*/
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            //页面下载完毕,却不代表页面渲染完毕显示出来
//            if (webview.getContentHeight() != 0) {
            //这个时候网页才显示
            //网页加载完成 在加载评论
            /*if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }*/
//            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            RceLog.d("lml","url="+url);
            // handle different requests for different type of files
            // this example handles downloads requests for .apk and .mp3 files
            // everything else the webview can handle normally
//            if (url.endsWith("isDowload=yes")) {
//                startActivity((new Intent(AnnouncementDetialActivity.this, ShowFileActivity.class))
//                        .putExtra("type", -1)
//                        .putExtra("id", -1)
//                        .putExtra("folderID", "workFlow")
//                        .putExtra("remotepath", url));
//            } else {
////                view.loadUrl(url);
//            }
            return false;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            //这里进行无网络或错误处理，具体可以根据errorCode的值进行判断，做跟详细的处理。
            view.loadUrl("file:///android_asset/error.html");
        }
    }




}
